/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* MmsMarketingProductlineInfoService
* 省区行销产品线配置信息表新
*
* 修改纪录
* 2021-07-08 版本：1.0 lvzhijun 创建。
* @version 版本：1.0
* @author 作者：lvzhijun
* 创建日期：2021-07-08
*/
package com.topscomm.mms.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.model.TreeModel;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.mms.pojo.MmsMarketingProductlineInfoEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.common.DatacodeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mms.service.IMmsMarketingProductlineInfoService;
import com.topscomm.mms.service.impl.auto.MmsMarketingProductlineInfoServiceAuto;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

@Service(value = "mmsMarketingProductlineInfoService")
@Scope(value = "singleton")
public class MmsMarketingProductlineInfoService extends MmsMarketingProductlineInfoServiceAuto implements IMmsMarketingProductlineInfoService {
    @Autowired
    private DatacodeCache datacodeCache;
    @Autowired
    private MmsProductBaseInfoService mmsProductBaseInfoService;
    @Autowired
    private MmsDeptExtraInfoService mmsDeptExtraInfoService;
    @Autowired
    private MmsProvinceMarketingInfoService mmsProvinceMarketingInfoService;
    /**
     * @description: 获取行销对应产品线数据
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @author: wangxinhua
     * @date: 2021/8/2 19:48
     * @modify:
     */
    @Override
    public Map<String, Object> getMarketingProductInfos(Map<String,Object> paramMap) {
        //获取行销岗位sql
        StringBufferProxy marketingSql = new StringBufferProxy();
        marketingSql.appendSingle(" enabled=1");
        //如果不是运营人员
        if(!checkIsOperators()) {
            // 获取当前人所在一级部门编号
            StringBufferProxy deptExtraSql = new StringBufferProxy();
            deptExtraSql.appendSingle(" {1}=1 and ({2}='{0}' or {3}='{0}' or {4}='{0}')",
                    getSessionUserBean().getUser().getCode(), MmsDeptExtraInfoEntity.FieldEnabled,
                    MmsDeptExtraInfoEntity.FieldProvincemanagercode, MmsDeptExtraInfoEntity.FieldCfocode,
                    MmsDeptExtraInfoEntity.FieldProvincechocode);
            List<MmsDeptExtraInfoEntity> extraInfoEntities = mmsDeptExtraInfoService.queryByWhere(deptExtraSql.toString());
            if (extraInfoEntities.size() > 0) {
                List<String> strDeptcommoncode = extraInfoEntities.stream().map(s -> s.getDeptcommoncode()).collect(Collectors.toList());
                if (paramMap.containsKey("qry_deptcommoncode1")) {
                    if(strDeptcommoncode.contains(ConvertUtil.convertToString(paramMap.get("qry_deptcommoncode1")))){
                        marketingSql.appendSingle(" and deptcommoncode1 ='" + ConvertUtil.convertToString(paramMap.get("qry_deptcommoncode1")) + "' ");
                    }else{
                        throw new ServiceException("您无权限查看当前省区数据");
                    }
                } else {
                    marketingSql.appendSingle(" and deptcommoncode1 ='" + extraInfoEntities.get(0).getDeptcommoncode() + "' ");
                }
            } else {
                throw new ServiceException("您无权限查看当前省区数据");
            }
        }else{
            if (paramMap.containsKey("qry_deptcommoncode1")) {
                marketingSql.appendSingle(" and deptcommoncode1 ='" + ConvertUtil.convertToString(paramMap.get("qry_deptcommoncode1")) + "' ");
            }else{
                List<MmsDeptExtraInfoEntity> extraInfoEntities = mmsDeptExtraInfoService.queryByWhere(" enabled=1 order by sortcode asc");
                marketingSql.appendSingle(" and deptcommoncode1 ='" + extraInfoEntities.get(0).getDeptcommoncode() + "' ");
            }
        }
        marketingSql.appendSingle(" order by  sortcode asc");
        //行销对应产品线
        List<Map<String,Object>> marketingProducts = this.queryMapByWhere(marketingSql.toString());
        //所有负责行销
        List<Map<String,Object>> marketingInfos = mmsProvinceMarketingInfoService.queryMapByWhere(marketingSql.toString());
        setDispFields(marketingInfos);
        //获取所有产品线对应的catalog1
        List<Map<String, Object>> allProductLineCataLog = this.queryMapByWhere("1=1", "queryProductCataLog1");
        setDispFields(allProductLineCataLog);
        List<Map<String,Object>> lineCataPostMapList = new ArrayList<Map<String,Object>>();
        for(Map<String, Object> lineCataLog :allProductLineCataLog){
            for(int i=0;i<marketingInfos.size();i++){
                Map<String,Object> copyMap = new HashMap<String,Object>();
                copyMap.putAll(lineCataLog);
                copyMap.put("marketingpost", marketingInfos.get(i).get("marketingpost"));
                lineCataPostMapList.add(copyMap);
            }
        }
        for(Map<String, Object> lcpItem :lineCataPostMapList){
            boolean isCheck = false;
            for(Map<String, Object> mpItem :marketingProducts){
                if (ConvertUtil.convertToString(mpItem.get("marketingpost")).equals(ConvertUtil.convertToString(lcpItem.get("marketingpost")))
                    && ConvertUtil.convertToString(mpItem.get("productline")).equals(ConvertUtil.convertToString(lcpItem.get("productline")))
                    && ConvertUtil.convertToString(mpItem.get("catalog1")).equals(ConvertUtil.convertToString(lcpItem.get("catalog1")))
                ) {
                    isCheck = true;
                }
            }
            if(isCheck){
                lcpItem.put("isCheck", "1");
            }else{
                lcpItem.put("isCheck", "0");
            }
        }
        for(Map<String, Object> lineCataLog2 :allProductLineCataLog){
            for(Map<String, Object> lcpItem2 :lineCataPostMapList){
                if (ConvertUtil.convertToString(lineCataLog2.get("productline")).equals(ConvertUtil.convertToString(lcpItem2.get("productline")))
                        && ConvertUtil.convertToString(lineCataLog2.get("catalog1")).equals(ConvertUtil.convertToString(lcpItem2.get("catalog1")))
                ) {
                    lineCataLog2.put("position_"+ ConvertUtil.convertToString(lcpItem2.get("marketingpost")),  ConvertUtil.convertToString(lcpItem2.get("isCheck")));
                }
            }
        }
        List<Map<String, Object>> listModules = new ArrayList<Map<String, Object>>();
        listModules = datacodeCache.getCodeListMap("ProductLine", "", "sortcode");
        //获取全部产品线信息
        for(Map<String, Object> codeItem : listModules){
            codeItem.put("children",new ArrayList<Map<String, Object>>());
            for(Map<String, Object> productInfo : allProductLineCataLog){
                if(ConvertUtil.convertToString(codeItem.get("code")).equals(ConvertUtil.convertToString(productInfo.get("productline")))){
                    List<Map<String, Object>> childrenList = (List<Map<String, Object>>)codeItem.get("children");
                    productInfo.put("name",productInfo.get("dispcatalog1"));
                    productInfo.put("code", "catloag" + productInfo.get("productline").toString() + productInfo.get("catalog1").toString());
                    childrenList.add(productInfo);
                    codeItem.put("children",childrenList);
                }
            }
            for(Map<String, Object> mpItem3 :marketingInfos){
                codeItem.put("productcheck_"+ ConvertUtil.convertToString(mpItem3.get("marketingpost")),  "0");
            }
        }
        Map<String,Object> resMap = new HashMap<String,Object>();
        resMap.put("tabledata",listModules);
        resMap.put("marketingInfos",marketingInfos);
        resMap.put("checkdata",marketingProducts);
        return resMap;
    }

    /**
     * @description: 保存行销岗位与产品线信息
     * @return void
     * @author: wangxinhua
     * @date: 2021/8/3 11:08
     * @modify:
     */
    @Override
    public void saveMarketingProductInfos(List<Map<String,Object>> tabledata,Map<String,Object> paramMap) {
        String updateDeptCommonCode = "";
        //如果不是运营人员
        if(!checkIsOperators()) {
            // 获取当前人所在一级部门编号
            StringBufferProxy deptExtraSql = new StringBufferProxy();
            deptExtraSql.appendSingle(" {1}=1 and ({2}='{0}' or {3}='{0}' or {4}='{0}')",
                    getSessionUserBean().getUser().getCode(), MmsDeptExtraInfoEntity.FieldEnabled,
                    MmsDeptExtraInfoEntity.FieldProvincemanagercode, MmsDeptExtraInfoEntity.FieldCfocode,
                    MmsDeptExtraInfoEntity.FieldProvincechocode);
            List<MmsDeptExtraInfoEntity> extraInfoEntities = mmsDeptExtraInfoService.queryByWhere(deptExtraSql.toString());
            if (extraInfoEntities.size() > 0) {
                List<String> strDeptcommoncode = extraInfoEntities.stream().map(s -> s.getDeptcommoncode()).collect(Collectors.toList());
                if (paramMap.containsKey("qry_deptcommoncode1")) {
                    if(strDeptcommoncode.contains(ConvertUtil.convertToString(paramMap.get("qry_deptcommoncode1")))){
                        updateDeptCommonCode = ConvertUtil.convertToString(paramMap.get("qry_deptcommoncode1"));
                    }else{
                        throw new ServiceException("您无权限查看当前省区数据");
                    }
                } else {
                    updateDeptCommonCode = extraInfoEntities.get(0).getDeptcommoncode();
                }
            } else {
                throw new ServiceException("您无权限查看当前省区数据");
            }
        }else{
            if (paramMap.containsKey("qry_deptcommoncode1")) {
                updateDeptCommonCode = ConvertUtil.convertToString(paramMap.get("qry_deptcommoncode1"));
            }else{
                List<MmsDeptExtraInfoEntity> extraInfoEntities = mmsDeptExtraInfoService.queryByWhere(" enabled=1 order by sortcode asc");
                updateDeptCommonCode = extraInfoEntities.get(0).getDeptcommoncode();
            }
        }
        List<Map<String,Object>> allChildren = new ArrayList<Map<String,Object>>();
        for(Map<String,Object> tdataItem : tabledata){
            List<Map<String,Object>> childrens = (List<Map<String,Object>>)tdataItem.get("children");
            allChildren.addAll(childrens);
        }
        List<BasicEntity> insertDataList = new ArrayList<BasicEntity>();
        for (Map<String,Object> childItem : allChildren){
            Set<String> set = childItem.keySet();
            for (String key:set) {
                if(key.contains("position_") && "1".equals(ConvertUtil.convertToString(childItem.get(key)))){
                    MmsMarketingProductlineInfoEntity  insertData = new MmsMarketingProductlineInfoEntity();
                    insertData.setDeptcommoncode1(updateDeptCommonCode);
                    List<String> poslist = Arrays.asList(key.split("_"));
                    insertData.setMarketingpost(poslist.get(1));
                    insertData.setProductline(ConvertUtil.convertToString(childItem.get("productline")));
                    insertData.setCatalog1(ConvertUtil.convertToString(childItem.get("catalog1")));
                    insertDataList.add(insertData);
                }
            }
        }
        this.deleteByWhere(" deptcommoncode1='"+updateDeptCommonCode+"' ");
        if(insertDataList.size()> 0 ){
            this.insertBatch(insertDataList);
        }
    }

    @Override
    protected void updateAfter(Map<String, Object> map) throws ServiceException {
        super.updateAfter(map);
        this.addValueToRedis(MmsMarketingProductlineInfoEntity.tableName);
    }

    @Override
    protected void afterInsert(BasicEntity entity) throws ServiceException {
        super.afterInsert(entity);
        this.addValueToRedis(MmsMarketingProductlineInfoEntity.tableName);
    }

    @Override
    protected void deleteAfter(String whereSql) {
        super.deleteAfter(whereSql);
        this.addValueToRedis(MmsMarketingProductlineInfoEntity.tableName);
    }
}
